package com.qzsoft.fileServers.serviceimpl;

import com.qzsoft.fileServers.dao.FileDao;
import com.qzsoft.fileServers.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    private static final String separator = File.separator;

    @Value("${com.qzsoft.fileServers.myFilePath}")
    private  String myFilePath;

    @Autowired
    private FileDao fileDao;

    @Override
    @Transactional
    public String saveBig(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw  new RuntimeException("文件不存在");
        } else if(file.getSize() <= 100*1024*1024){
            throw  new RuntimeException("文件小于100M无法上传");
        }
        return save(file);
    }

    @Override
    @Transactional
    public String saveSmall(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw  new RuntimeException("文件不存在");
        } else if(file.getSize() > 100*1024*1024){
            throw  new RuntimeException("文件大于100M无法上传");
        }
        return save(file);
    }

    @Override
    public void get(String id, HttpServletResponse res) throws Exception {
        com.qzsoft.fileServers.entity.File file = fileDao.getById(id);
        if(file == null){
            throw new RuntimeException("文件不存在");
        }
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(),"UTF-8"));
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(file.getCreatTime());
            Calendar cale = Calendar.getInstance();//日历对象
            cale.setTime(date);//设置当前日期
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(getFile(file)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } finally {
            if(os != null){
                os.close();
            }
            if(bis != null){
                bis.close();
            }
        }
    }

    @Override
    @Transactional
    public void delete(String id) throws Exception {
        com.qzsoft.fileServers.entity.File fileData = fileDao.getById(id);
        if(fileData == null){
            throw new RuntimeException("文件不存在");
        }
        File file = getFile(fileData);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (!file.delete()) {
                throw new RuntimeException("删除文件" + fileData.getName() + fileData.getType() + "失败");
            }
            fileDao.delete(id);
        } else {
            throw new RuntimeException("文件" + fileData.getName() + fileData.getType() + "不存在");
        }
    }

    public File getFile(com.qzsoft.fileServers.entity.File file) throws Exception{
        Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(file.getCreatTime());
        Calendar cale = Calendar.getInstance();//日历对象
        cale.setTime(date);//设置当前日期
       return new File(myFilePath + "fileServers" + separator +
                String.valueOf(cale.get(Calendar.YEAR)) +
                String.valueOf((cale.get(Calendar.MONTH) + 1) > 9 ?
                        String.valueOf(cale.get(Calendar.MONTH) + 1) : "0" +
                        String.valueOf(cale.get(Calendar.MONTH) + 1)) +
               separator +  (cale.get(Calendar.DATE) > 9 ?
                String.valueOf(cale.get(Calendar.DATE)) : "0" +
                String.valueOf(cale.get(Calendar.DATE))) + separator
                +  file.getId() + file.getType());
    }

    public String save (MultipartFile file) throws Exception{
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //保存文件信息到数据库
        com.qzsoft.fileServers.entity.File fe = new com.qzsoft.fileServers.entity.File();
        fe.setId(UUID.randomUUID().toString());
        fe.setName(fileName);
        fe.setType(suffixName);
        fe.setCreatTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
        Calendar cale = Calendar.getInstance();
        String paper = String.valueOf(cale.get(Calendar.YEAR)) + ((cale.get(Calendar.MONTH) + 1) > 9 ? String.valueOf(cale.get(Calendar.MONTH) + 1) : "0" + String.valueOf(cale.get(Calendar.MONTH) + 1)) ;
        paper += separator + (cale.get(Calendar.DATE) > 9 ?  String.valueOf(cale.get(Calendar.DATE)) : "0" + String.valueOf(cale.get(Calendar.DATE)));
        // 设置文件存储路径
        String filePath = myFilePath + separator + "fileServers" + separator + paper;
        File dest = new File(filePath,fe.getId() + fe.getType());
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();// 新建文件夹
        }
        file.transferTo(dest);// 文件写入
        fileDao.save(fe);
        return fe.getId();
    }
}
